package cn.ekgc.bmdsad.day13;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpChat {
    static Scanner input = new Scanner(System.in);
    public static void main(String[] args) {
        try (DatagramSocket ds = new DatagramSocket(8080)) {
            new Thread(()->{
                byte[] buffer = new byte[1024];
                DatagramPacket p = new DatagramPacket(buffer,buffer.length);

                while (true){
                    try {
                        ds.receive(p);
                        System.out.println(new String(p.getData(),0,p.getLength()));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            }).start();
            new Thread(()->{
                DatagramPacket p=null;
                while (true){
                    //吃饭了吗@192.168.110.12
                    String line = input.nextLine();
                    String[] ss = line.split("@");

                    try {
                        InetAddress inetAddress = InetAddress.getByName(ss[1]);
                        p=new DatagramPacket(ss[0].getBytes(),0,ss[0].getBytes().length,inetAddress,8080);
                        ds.send(p);

                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }


            }).start();


            synchronized ("a"){
                "a".wait();
            }

        } catch (SocketException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
